{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 381,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests as rq\n",
    "import time\n",
    "import random\n",
    "import string\n",
    "import urllib\n",
    "import hashlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 423,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "APPKEY = 'abcdefghijk'  # 替换成你的appkey！！！\n",
    "APPID = 1234567890  # 替换成你的appid！！！\n",
    "\n",
    "def get_sign(data):\n",
    "    lst = [i[0]+'='+urllib.parse.quote_plus(str(i[1])) for i in data.items()]\n",
    "    params = '&'.join(sorted(lst))\n",
    "    s = params + '&app_key=' + APPKEY\n",
    "    h = hashlib.md5(s.encode('utf8'))\n",
    "    return h.hexdigest().upper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 424,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pyaudio\n",
    "import wave\n",
    "import base64\n",
    "\n",
    "FORMAT = pyaudio.paInt16\n",
    "CHANNELS = 2\n",
    "RATE = 8000#44100\n",
    "CHUNK = 1024\n",
    "RECORD_SECONDS = 3\n",
    "\n",
    "def record():\n",
    "    # start Recording\n",
    "    stream = audio.open(format=FORMAT, channels=CHANNELS,\n",
    "                    rate=RATE, input=True,\n",
    "                    frames_per_buffer=CHUNK)\n",
    "    print(\"listening...\")\n",
    "    frames = [] \n",
    "    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n",
    "        data = stream.read(CHUNK)\n",
    "        frames.append(data)\n",
    "    # stop Recording\n",
    "    stream.stop_stream()\n",
    "    stream.close()\n",
    "\n",
    "    voice = b''.join(frames)\n",
    "    b64voice = base64.b64encode(voice)\n",
    "\n",
    "    url_asr = 'https://api.ai.qq.com/fcgi-bin/aai/aai_asr'\n",
    "    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))\n",
    "    data = {\n",
    "        'app_id': APPID,\n",
    "        'time_stamp': int(time.time()),\n",
    "        'nonce_str': nonce_str,\n",
    "        'format': 1,\n",
    "        'speech': b64voice.decode(),\n",
    "    }\n",
    "    data['sign'] = get_sign(data)\n",
    "    r = rq.post(url_asr, data=data)\n",
    "    question = r.json()['data']['text']\n",
    "    return question"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 384,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def chat(question):    \n",
    "    url_chat = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat'\n",
    "    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))\n",
    "    data = {\n",
    "        'app_id': APPID,\n",
    "        'time_stamp': int(time.time()),\n",
    "        'nonce_str': nonce_str,\n",
    "        'session': '10000',\n",
    "        'question': question,\n",
    "    }\n",
    "    data['sign'] = get_sign(data)\n",
    "    r = rq.post(url_chat, data=data)\n",
    "    answer = r.json()['data']['answer']\n",
    "    return answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 385,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def playsound(voice):\n",
    "    stream = audio.open(\n",
    "        format = FORMAT,\n",
    "        channels = CHANNELS,\n",
    "        rate = RATE,\n",
    "        output = True)\n",
    "    stream.write(voice)\n",
    "    stream.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 386,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def speak(text):\n",
    "    text = text[:50]\n",
    "    url_speak = 'https://api.ai.qq.com/fcgi-bin/aai/aai_tts'\n",
    "    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))\n",
    "    data = {\n",
    "        'app_id': APPID,\n",
    "        'time_stamp': int(time.time()),\n",
    "        'nonce_str': nonce_str,\n",
    "        'text': text,\n",
    "        'speaker': 1,\n",
    "        'format': 2,\n",
    "        'volume': 0,\n",
    "        'speed': 100,\n",
    "        'aht': 0,\n",
    "        'apc': 58,\n",
    "    }\n",
    "    data['sign'] = get_sign(data)\n",
    "    r = rq.post(url_speak, data=data)\n",
    "    voice = r.json()['data']['speech']\n",
    "    voice = base64.b64decode(voice)\n",
    "    playsound(voice)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 394,
   "metadata": {},
   "outputs": [],
   "source": [
    "def face(img_file, model):\n",
    "    with open(img_file, 'rb') as f:\n",
    "        img = base64.b64encode(f.read())\n",
    "    url_face = 'https://api.ai.qq.com/fcgi-bin/ptu/ptu_facemerge'\n",
    "    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))\n",
    "    data = {\n",
    "        'app_id': APPID,\n",
    "        'time_stamp': int(time.time()),\n",
    "        'nonce_str': nonce_str,\n",
    "        'model': model,\n",
    "        'image': img.decode(),\n",
    "    }\n",
    "    data['sign'] = get_sign(data)\n",
    "    r = rq.post(url_face, data=data)\n",
    "    pic = r.json()['data']['image']\n",
    "    return pic\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "audio = pyaudio.PyAudio()\n",
    "for i in range(5):\n",
    "    question = record()\n",
    "    print(question)\n",
    "    answer = chat(question)\n",
    "    print(answer)\n",
    "    speak(answer)\n",
    "#     time.sleep(1)\n",
    "audio.terminate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import io\n",
    "from PIL import Image\n",
    "p = face('head.jpg', 22)\n",
    "image=io.BytesIO(base64.b64decode(p))\n",
    "img = Image.open(image)\n",
    "img.show()\n",
    "# img"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
